package yannuo.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DriudUtil {

    public static Connection getConnection() throws Exception {
        //加载属性文件 db.properties
        Properties prop = new Properties();
        prop.load(new FileInputStream("E:\\ideaworkspace\\java141work\\javaworkspace\\javaee03\\src\\db.properties"));
//        for (Map.Entry<Object, Object> mapss : prop.entrySet()) {
//            String key = (String) mapss.getKey();
//            String value = (String) mapss.getValue();
//            System.out.println(key+"-->"+value);
//        }
        //通过Driud数据库工厂获取DataSource
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        //获取Connection
        Connection connection = dataSource.getConnection();
        return connection;
    }

    public static void closeAll(ResultSet rs, Statement st, Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
